import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import Dashboard from '@/views/Dashboard.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true },
    children: [
      {
        path: '/',
        name: 'Dashboard',
        component: Dashboard,
        meta: { requiresAuth: true }
      },
      {
        path: '/servers',
        name: 'Servers',
        component: () => import('@/views/Servers.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/migrations',
        name: 'Migrations',
        component: () => import('@/views/Migrations.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/logs',
        name: 'Logs',
        component: () => import('@/views/Logs.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/reports',
        name: 'Reports',
        component: () => import('@/views/Reports.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/user-stats',
        name: 'UserStats',
        component: () => import('@/views/UserStats.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/users/:id',
        name: 'UserDetail',
        component: () => import('@/views/UserDetail.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/user-import',
        name: 'UserImport',
        component: () => import('@/views/UserImport.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/backups',
        name: 'Backups',
        component: () => import('@/views/Backups.vue'),
        meta: { requiresAuth: true }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth) {
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    if (to.path === '/login' && token) {
      next('/')
    } else {
      next()
    }
  }
})

// 添加全局路由错误处理
router.onError((error) => {
  if (error.name === 'NavigationDuplicated' || error.message.includes('Navigation cancelled')) {
    // 忽略导航重复和取消错误
    console.warn('路由导航被取消或重复:', error)
  } else {
    console.error('路由错误:', error)
  }
})

export default router